package com.book.book.controller;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.book.book.domain.CategoryDO;
import com.book.book.domain.UsersDO;
import com.book.book.service.CategoryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.mapping.Indexed;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.book.book.domain.BooksDO;
import com.book.book.service.BooksService;
import com.book.common.utils.PageUtils;
import com.book.common.utils.Query;
import com.book.common.utils.R;

import javax.servlet.http.HttpServletRequest;

/**
 * 图书商品表
 *
 * @author siyuan
 * @email 894266364.com
 * @date 2018-01-27 10:53:23
 */

@Controller
@RequestMapping("/book/books")
public class BooksController {
    @Autowired
    private BooksService booksService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SolrClient client;

    //分类map
    Map<String,List<CategoryDO>> categoryMap = new LinkedHashMap<>();

    @GetMapping()
    @RequiresPermissions("book:books:books")
    String Books() {
        return "book/books/books";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("book:books:books")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        int total1 = booksService.count(query);
        List<BooksDO> booksList = booksService.listWithName(query);
        //带有userName的查询
//        List<BooksDO> booksList = booksService.listWithName(query);
        int total = booksService.count(query);
        PageUtils pageUtils = new PageUtils(booksList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("book:books:add")
    String add(Model model) {
        //所有分类
        if (categoryMap.isEmpty()) {
            List<CategoryDO> categoryDOList = categoryService.list(null);
            categoryMap.put("categoryDOList",categoryDOList);
        }
        model.addAttribute("categoryDOList",categoryMap.get("categoryDOList"));
        return "book/books/add";
    }

    @GetMapping("/edit/{bookId}")
    //	@RequiresPermissions("book:books:edit")
    String edit(@PathVariable("bookId") Integer bookId, Model model) {
        BooksDO books = booksService.get(bookId);
        model.addAttribute("books", books);
        if (categoryMap.isEmpty()) {
            List<CategoryDO> categoryDOList = categoryService.list(null);
            categoryMap.put("categoryDOList",categoryDOList);
        }
        model.addAttribute("categoryDOList",categoryMap.get("categoryDOList"));
        return "book/books/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("book:books:add")
    public R save(BooksDO books) throws IOException, SolrServerException {
        if (books == null){
            return R.error("请填写相关内容后再提交");
        }
        if (booksService.save(books) > 0) {
            // 定义数据 solr输入文档 数据结构为Map
            SolrInputDocument inputDocument = new SolrInputDocument();
            inputDocument.addField("id",books.getBookId());
            inputDocument.addField("book_name", books.getBookName());
            inputDocument.addField("author2",books.getAuthor());
            inputDocument.addField("book_img",books.getBookImg());
            // 执行添加 ps：如果id相同，则执行更新操作
            // 要指定操作的collection 就是solr-home下定义的core
            UpdateResponse add = client.add("collection1", inputDocument);
            //提交添加/更新
            client.commit("collection1");

            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
//	@RequiresPermissions("book:books:edit")
    public R update(BooksDO books) throws IOException, SolrServerException {
        booksService.update(books);
        // 先删除solr 数据库中的 索引
        // 通过id删除 执行要删除的collection（core）
        client.deleteById("collection1", books.getBookId());
        // 还可以通过查询条件删除
        // solrClient.deleteByQuery("RoleVO", "查询条件");
        // 提交删除
        client.commit("collection1");

        // 添加数据库索引
        // 定义数据 solr输入文档 数据结构为Map
        SolrInputDocument inputDocument = new SolrInputDocument();
        inputDocument.addField("id",books.getBookId());
        inputDocument.addField("book_name", books.getBookName());
        inputDocument.addField("author2",books.getAuthor());
        inputDocument.addField("book_img",books.getBookImg());
        // 执行添加 ps：如果id相同，则执行更新操作
        // 要指定操作的collection 就是solr-home下定义的core
        UpdateResponse add = client.add("collection1", inputDocument);
        //提交添加/更新
        client.commit("collection1");
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
//    @RequiresPermissions("book:books:remove")
    public R remove(Integer bookId) throws IOException, SolrServerException {
        if (booksService.remove(bookId) > 0) {
            //通过id删除 执行要删除的collection（core）
            client.deleteById("collection1", bookId);
            // 还可以通过查询条件删除
            // solrClient.deleteByQuery("RoleVO", "查询条件");
            // 提交删除
            client.commit("collection1");
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("book:books:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] bookIds) throws IOException, SolrServerException {


        booksService.batchRemove(bookIds);
           //暂时不提供删除所有，，，，删除数据库来的更直接
         //  默认不开放这个接口
         //  client.deleteById("collection1");
          // client.commit();

         return R.ok();
    }

    @GetMapping("/wish")
    String catWishHtml() {
//        redisTemplate.opsForValue().append("a","asdd");
        return "book/phone/html/用户心愿";
    }



}
